package cn.edu.zstu.qingzhu.qingzhushop.handler;

import cn.edu.zstu.qingzhu.qingzhushop.entity.AuthenticationUser;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Log;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.service.ILogService;
import cn.edu.zstu.qingzhu.qingzhushop.util.IPUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-07-28 21:04
 */
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    ILogService iLogService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String ip = IPUtil.getIPAddress(request);
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        Log loginLog = new Log();
        loginLog.setOperation("登出");
        loginLog.setType("logout");
        loginLog.setIp(ip);
        loginLog.setOperator(user.getUsername());
        loginLog.setTime(LocalDateTime.now());
        loginLog.setStatus("success");
        loginLog.setRemark("登出成功!");
        iLogService.save(loginLog);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(ResponseBean.ok("注销成功!")));
        out.flush();
        out.close();
    }
}
